<?php
/**
 *
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/21 0021
 * Time: 15:15
 * 用户注册商铺列表
 */

namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\Shop as Shops;
use think\Db;
use think\Model;

class Shop extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * @apiGroup test
     * @apiName  shop_index
     * @api {post} /api/shop/index  店铺列表，检索接口
     * @apiparam {string}  shop_type    维修站1,2,检查站2
     * @apiparam {string} star_class    星级
     * @apiparam {string} distance_type 距离类别传1，2，3表示为1：500m 以内 2：500-10000密码 3:1000米以上
     * @apiparam {string} page       当前页数
     * @apiparam {string} pagenum       一页多少条
     * @apiparam {string} shop_name     可选店铺id
     * @apiparam  {string} longitude   可选经度
     * @apiparam  {string} latitude    可选维度
     * @apiparam  {string} ordertype  可选传 distance_n按照距离降序排序 distance_u:按照距离升序排序star_n:按照星级降序排序  star_u:按照星级升序序排序默认id降序排序
     * @apiSuccessExample Success-Response:
     * {"code":1,"msg":"返回成功","time":"1576136284","data":[{"id":1,"shop_name":"测试","shop_user":"王二","shop_image":"\/assets\/img\/qrcode.png","persion_consume":70,"star_class":4,"tags":"维修,修车","description":"是的发生的","address":"山东","province":"山东","city":"安徽省\/芜湖市","area":"333","longitude":"120.400368","latitude":"36.108348","shop_phone":"53233333","distance":334},{"id":2,"shop_name":"测试","shop_user":"23","shop_image":"\/uploads\/20191212\/cdecfee0440353aa24c7b18d100d59ca.jpg","persion_consume":3,"star_class":3,"tags":"2","description":"3","address":"d","province":"山东","city":"","area":"3","longitude":"2","latitude":"3","shop_phone":"53233333","distance":12598179}]}
     */
    public function index()
    {
        $shop_name = $this->request->post('shop_name');
        $lng = $this->request->post('longitude');
        $lat = $this->request->post('latitude');
        $ordertype = $this->request->post('ordertype');
        $page = $this->request->post('page');
        $pagenum = $this->request->post('pagenum');
        $shop_type = $this->request->post('shop_type');
        $star_class = $this->request->post('star_class');
        $distance_type = $this->request->post('distance_type');
        switch ($ordertype) {
            case $ordertype == 'star_n':
                $str_desc = 'star_class desc';
                break;
            case $ordertype == 'star_u':
                $str_desc = 'star_class asc';
                break;
            default :
                $str_desc = 'id desc';
        }
        $map = [];
        if ($shop_type) {
            $map['shop_type'] = $shop_type;
        }
        if ($shop_name) {
            $map['shop_name'] = ['like', $shop_name . '%'];
        }
        if ($star_class) {
            $map['star_class'] = $star_class;
        }

        $lists = Db::name('shop')->field('id,shop_name,shop_user,persion_consume,star_class,tags,description,address,province,city,longitude,latitude,shop_phone,shop_type')->order($str_desc)->where($map)->page($page, $pagenum)->select();

        if (!empty($lng) && !empty($lat)) {
            foreach ($lists as $k => &$v) {
                $lat2 = $v['latitude']; //经度
                $long2 = $v['longitude']; //经度
                if ($lat2 && $long2) {
                    //  $distance = GetDistance($lat, $lng, $lat2, $long2);
                    //根据腾讯api 算距离
                    $key = 'QRRBZ-H536U-PADVB-2SCXX-RJ3AK-CFF4O';
                    $url = 'https://apis.map.qq.com/ws/distance/v1/?mode=driving&from=' . $lat . ',' . $lng . '&to=' . $lat2 . ',' . $long2 . '&key=' . $key;
                    $result = json_decode(file_get_contents($url), true);
                    //print_r($result);
                    $distance = $result['result']['elements']['0']['distance'];
                    if ($distance_type == '1') {
                        if ($distance < '500') {
                            $v['distance'] = $distance;

                        } else {
                            unset($lists[$k]);
                        }
                    } elseif ($distance_type == '2') {
                        if (('500' < $distance) and ($distance < '1000')) {
                            $v['distance'] = $distance;
                        } else {
                            unset($lists[$k]);
                        }
                    } else if ($distance_type == '3') {
                        if ($distance > '1000') {
                            $v['distance'] = $distance;
                        } else {
                            unset($lists[$k]);
                        }
                    }else{
                        $v['distance'] = $distance;
                    }
                } else {
                    $v['distance'] = '该店铺没有设置经纬度';
                }
            }
        }
        if ($ordertype == 'distance_n') {
            $last_distance = array_column($lists, 'distance');
            array_multisort($last_distance, SORT_DESC, $lists);
        }
        if ($ordertype == 'distance_u') {
            $last_distance = array_column($lists, 'distance');
            array_multisort($last_distance, SORT_ASC, $lists);
        }
        //  $lists['count'] = $count;
        $this->success('返回成功', $lists);

    }

    /**
     * @apiGroup test
     * @apiName  shop_index_detail
     * @api {post} /api/shop/shop_index_detail  首页点击出详情
     * @apiparam {string} id       店铺id
     * @apiparam  {string} longitude 经度
     * @apiparam  {string} latitude    维度
     * @apiSuccessExample Success-Response:
     * {"code":1,"msg":"返回成功","time":"1575969212","data":[{"id":1,"shop_name":"测试","shop_user":"王二","shop_image":"\/assets\/img\/qrcode.png","persion_consume":70,"star_class":4,"tags":"维修,修车","description":"是的发生的","address":"山东","province":"山东","city":"安徽省\/芜湖市","area":"333","longitude":"3434","latitude":"22","shop_phone":"53233333"}]}
     */
    public function shop_index_detail()
    {
        $id = $this->request->post('id');
        $lng = $this->request->post('longitude');
        $lat = $this->request->post('latitude');
        $model = model('shop');
        $list = $model->field('id,shop_name,shop_user,shop_image,persion_consume,star_class,tags,description,address,province,city,longitude,latitude,shop_phone')
            ->order('id desc')->limit(0, 10)->where('id', $id)->find();
        // print_r($list);
        //   $lng = '120.39972';
        // $lat = '36.114146';
        $lat2 = $list->latitude; //维度
        $long2 = $list->longitude; //经度
        if($lat && $lng) {
            $key = 'QRRBZ-H536U-PADVB-2SCXX-RJ3AK-CFF4O';
            $url = 'https://apis.map.qq.com/ws/distance/v1/?mode=driving&from=' . $lat . ',' . $lng . '&to=' . $lat2 . ',' . $long2 . '&key=' . $key;
            $result = json_decode(file_get_contents($url), true);
            $distance = $result['result']['elements']['0']['distance'];
            //  $distance = GetDistance($lat, $lng, $lat2, $long2);
            $list->distance = $distance;
        }
        $this->success('返回成功', $list);
    }

    /**
     * @apiGroup test
     * @apiName  shop_detail
     * @api {post} /api/shop/shop_detail  店铺详情
     * @apiDescription  返回 comment 评论数  type_comment 评论种类 status 0 收藏成功 1取消收藏 show_star 店铺评级数 （前台所有用户评论的总分/评论次数 + 后台管理的总分）\200 一星160分 总分1000 后台占800
     * @apiparam {string} id       店铺id
     * @apiparam {string} user_id     用户id
     * @apiparam  {string} longitude 经度
     * @apiparam  {string} latitude    维度
     * @apiSuccessExample Success-Response:
     * {"code":1,"msg":"返回成功","time":"1576632085","data":{"detail":{"id":1,"shop_name":null,"shop_mobile":"13240746617","business_hour":"周一至周日 8点-21点","description":null,"shop_user":"王二","shop_image":"122.jpg","shop_image2":"2.jpg","shop_image3":"3.jpg","persion_consume":70,"star_class":null,"tags":null,"address":"山东","province":null,"city":null,"area":null,"longitude":"120.02584362955","latitude":"36.305678777723","shop_phone":null,"hb_shop_image":"[\"122.jpg\",\"2.jpg\",\"3.jpg\"]"},"comment":2,"type_comment":[{"shop_comment_type_num":3,"name":"技术不错"},{"shop_comment_type_num":4,"name":"服务热情"}]}}
     */
    public function shop_detail()
    {
        $id = $this->request->post('id');
        $user_id = $this->request->post('user_id');
        $lng = $this->request->post('longitude');
        $lat = $this->request->post('latitude');
        $c['shop_id'] = $id;
        $c['user_id'] = $user_id;
        $collection = Db::name('collection')->where($c)->find();
        $model = model('shop');
        $list = $model->field('id,shop_name,shop_mobile,business_hour,description,shop_user,shop_image,shop_2image,shop_3image,persion_consume,star_class,tags,description,address,province,city,longitude,latitude,shop_phone')
            ->order('id desc')->limit(0, 10)->where('id', $id)->find();

        $list['hb_shop_image'] = [$list['shop_image'], $list['shop_2image'],$list['shop_3image']];
        //  $lng = '120.411530';
        // $lat = '36.099880';
        if ($lat && $lng) {
            $lat2 = $list->latitude; //维度
            $long2 = $list->longitude; //经度
            $key = 'QRRBZ-H536U-PADVB-2SCXX-RJ3AK-CFF4O';
            $url = 'https://apis.map.qq.com/ws/distance/v1/?mode=driving&from=' . $lat . ',' . $lng . '&to=' . $lat2 . ',' . $long2 . '&key=' . $key;
            $result = json_decode(file_get_contents($url), true);
            $distance = $result['result']['elements']['0']['distance'];
            //  $distance = GetDistance($lat, $lng, $lat2, $long2);
            $list->distance = $distance;
        }
        $list['status'] = $collection['status'];
        $arr = array();
        $arr['detail'] = $list;
        $comment = Db::name('shop_comment')->where('shop_id', $id)->count();
        $arr['comment'] = $comment;
        $type_comment = Db::name('shop_comment_num')->alias('c')->field('shop_comment_type_num,name')->join('__SHOP_COMMENT_TYPE__ t', 'c.shop_comment_type_id = t.id', 'left')->where('c.shop_id', $id)->select();
        $arr['type_comment'] = $type_comment;
        //获取评论
		$comment_list = Db::name('shop_comment')->alias('s')->where('s.shop_id', $id)->join('__WECHATUSER__ w', 's.user_id = w.id')->field('s.id,nickName,avatarUrl,content,star,comment_img,spotnum,s.addtime')->limit(0, 1)->select();
		$arr['comment_list'] = $comment_list;
        //获取店铺评级
        $sum_comment = Db::name('shop_comment')->where('shop_id',$id)->sum('star');
        $star_class = $list['star_class'];
        //店铺点铺星级计算公式 （前台所有用户评论的总分/评论次数 + 后台管理的总分）\200 一星160分 总分1000 后台占800

         $h_grade = $star_class * 150;
		 if($comment != 0){
			$show_star= round((($sum_comment*150)/$comment +$h_grade)/200,1);
		 }else{
			 	$show_star= round(($h_grade)/200,1);
		 }
         $arr['show_star'] = $show_star;
        $this->success('返回成功', $arr);
    }

    /**
     * @apiGroup test
     * @apiName  shop_comment
     * @api {post} /api/shop/shop_comment  进行店铺评论
     * @apiparam {string} shop_id       店铺id
     * @apiparam  {string} user_id     用户id
     * @apiparam  {string} content    评论内容
     * @apiparam  {string} comment_img    评论图片 [
     * "1.jpg",
     * "2.jpg",
     * "3.jpg"
     * ]
     * @apiparam  {string} star    评论星级
     * @apiSuccessExample Success-Response:
     * {"code":1,"msg":"返回成功","time":"1576139162",}
     */
    public function shop_comment()
    {
	
        $maps['shop_id'] = $this->request->post('shop_id');
        $maps['user_id'] = $this->request->post('user_id');
        $data = Db::name('shop_comment')->where($maps)->find();
     //   if (!$data) {
            $maps['content'] = $this->request->post('content');
            $comment_img = $this->request->post('comment_img');

            if ($comment_img) {
                //$comment_image_arr = json_decode(htmlspecialchars_decode($comment_img), true);
               // $comment_image_arr = implode($comment_image_arr, '|');
                $maps['comment_img'] = $comment_img;
            }
            $maps['star'] = $this->request->post('star');
            $maps['addtime'] = date('Y-m-d H:i:s', time());
            $result = Db::name('shop_comment')->insert($maps);
            if ($result) {
                $this->success('返回成功');
            } else {
                $this->success('评论失败');
            }
      //  } else {
       //     $this->error('已经评论成功,无需重复评论');
       // }

    }

    /**
     * @apiGroup test
     * @apiName  shop_login
     * @apiDescription  可用 手机号 13240746617 密码 123456 测试登录 返回shop_id 用于获取店铺详情
     * @api {post} /api/shop/shop_login  店铺登录
     * @apiparam {string} shop_mobile       店铺负责人手机号
     * @apiparam  {string} shop_password     店铺密码
     * @apiSuccessExample Success-Response:
     * {"code":1,"msg":"返回成功","time":"1576389735","data":{"shop_id":1}}
     */

    public function shop_login()
    {
        $map = array();
        $map['shop_mobile'] = $this->request->post('shop_mobile');
        $map['shop_passwd'] = $this->request->post('shop_password');
        $data = Db::name('shop')->where($map)->find();
        $shop_id = $data['id'];
        if ($data) {
            $this->success('返回成功', ['shop_id' => $shop_id]);
        } else {
            $this->error('返回失败');
        }
    }

    /**
     * @apiGroup test
     * @apiName  shop_edit
     * @apiDescription  店铺编辑
     * @api {post} /api/shop/shop_edit  店铺编辑
     * @apiparam {string} shop_id       店铺id
     * @apiparam {string} shop_name     店铺名字
     * @apiparam {string} hb_shop_image    店铺图片格式为 三张图片[
     * "1.jpg",
     * "2.jpg",
     * "3.jpg"
     * ]
     * @apiparam {string} star_class    店铺星级
     * @apiparam {string} tags         店铺标签
     * @apiparam {string} description   店铺描述
     * @apiparam {string} longitude       店铺经度
     * @apiparam {string} latitude       店铺纬度
     * @apiparam {string} shop_phone       店铺电话
     * @apiparam {string} address      住址  会根据腾讯住址得到经纬度
     * @apiSuccessExample Success-Response:
     * {"code":1,"msg":"返回成功","time":"1576389735","data":{"shop_id":1}}
     */

    public function shop_edit()
    {
        $map = array();
        $address = $this->request->post('address');
        if ($address) {
            $map['address'] = $address;
            $key = 'QRRBZ-H536U-PADVB-2SCXX-RJ3AK-CFF4O';
            $url = 'https://apis.map.qq.com/ws/geocoder/v1/?address=' . $address . '&output=json&key=' . $key . '&callback=function1';
            $dt = file_get_contents($url);

            $dt_arr = json_decode($dt, true);
            if ($dt_arr['status'] == '0') {
                $lng = $dt_arr['result']['location']['lng'];
                $lat = $dt_arr['result']['location']['lat'];
                $map['longitude'] = $lng;
                $map['latitude'] = $lat;
            }
        }
        $shop_image = $this->request->post('hb_shop_image');
        if ($shop_image) {
           // $shop_image_arr = json_decode(htmlspecialchars_decode($shop_image), true);
			  if (stripos($shop_image, ',') >= 0) {
                 $shop_image_arr = explode(',', $shop_image);
				 if (!empty($shop_image_arr)) {
                if (isset($shop_image_arr['0'])) {
                    $map['shop_image'] = $shop_image_arr['0'];
                }
                if (isset($shop_image_arr['1'])) {
                    $map['shop_2image'] = $shop_image_arr['1'];
                }
                if (isset($shop_image_arr['2'])) {
                    $map['shop_3image'] = $shop_image_arr['2'];
                }
            }
            }else{
				$map['shop_image'] = $shop_image;
			}
       
			
        }


        $arr['id'] = $this->request->post('shop_id');
        $map['shop_name'] = $this->request->post('shop_name');
        $map['tags'] = $this->request->post('tags');
        $map['description'] = $this->request->post('description');
        $map['shop_phone'] = $this->request->post('shop_phone');
        $map['province'] = $this->request->post('province');
        $map['shop_user'] = $this->request->post('shop_user');
        $map['business_hour'] = $this->request->post('business_hour');
        $map['description'] = $this->request->post('description');
        $map['city'] = $this->request->post('city');
        $data = Db::name('shop')->where($arr)->update($map);
        if ($data) {
            $this->success('返回成功');
        } else {
            $this->success('已经更新过了，请修改数据在提交');
        }

    }

    /**
     * @apiGroup test
     * @apiName  common_list
     * @apiDescription  店铺评论列表  返回的count评论条数 spotnum 点赞数
     * @api {post} /api/shop/common_list  店铺评论列表
     * @apiparam {string} shop_id       店铺id
     * @apiparam {string} page       当前页数
     * @apiparam {string} pagenum       一页多少条
     * @apiparam {string} user_id       用户id
     * @apiSuccessExample Success-Response:
     * {{"code":1,"msg":"返回成功","time":"1576547801","data":[{"nickName":"23423","avatarUrl":"23dfd23423454","content":"dfdfd","star":3,"comment_img":"dfdfd"}]}
     */
    public function common_list()
    {

        $shop_id = $this->request->post('shop_id');
        $user_id = $this->request->post('user_id');
        $page = $this->request->post('page');
        $pagenum = $this->request->post('pagenum ');
        $count = Db::name('shop_comment')->alias('s')->where('s.shop_id', $shop_id)->join('__WECHATUSER__ w', 's.user_id = w.id')->count();
        $data = Db::name('shop_comment')->alias('s')->where('s.shop_id', $shop_id)->join('__WECHATUSER__ w', 's.user_id = w.id')->field('s.id,nickName,avatarUrl,content,star,comment_img,spotnum,s.addtime')->page($page, $pagenum)->select();
        //  echo json_encode($data);
        $map = array();
        foreach ($data as $k => $v) {
            $spot['user_id'] = $user_id;
            $spot['comment_id'] = $v['id'];
            $spot = Db::name('shop_comment_spot')->where($spot)->find();
            $map[$k]['status'] = $spot['status'];
            $map[$k]['id'] = $v['id'];
            $map[$k]['nickName'] = $v['nickName'];
            $map[$k]['avatarUrl'] = $v['avatarUrl'];
            $map[$k]['content'] = $v['content'];
            $map[$k]['star'] = $v['star'];
            $map[$k]['spotnum'] = $v['spotnum'];
            $map[$k]['addtime'] = $v['addtime'];
            if (strpos($v['comment_img'], ',')) {
                $map[$k]['comment_img'] = explode(',', $v['comment_img']);
            } else {
                if ($v['comment_img']) {
                    $map[$k]['comment_img'] = [$v['comment_img']];
                } else {
                    $map[$k]['comment_img'] = [];
                }
            }

        }
        // echo json_encode($map);
        //    die();
        // $map['count'] = $count;

        if ($map) {
            $this->success('返回成功', $map);
        } else {
            $this->error('返回数据失败');
        }
    }

    /**
     * @apiGroup test
     * @apiName  common_spot
     * @apiDescription  店铺评论用户点赞
     * @api {post} /api/shop/common_spot  店铺评论用户点赞
     * @apiparam {string} comment_id       评论id 为店铺评论列表返回的id
     * @apiparam {string} user_id       用户id
     * @apiparam {string} status       可选 不传为点赞 ，传1 为取消点赞
     * @apiSuccessExample Success-Response:
     * {{"code":1,"msg":"返回成功","time":"1576547801","data":[{"nickName":"23423","avatarUrl":"23dfd23423454","content":"dfdfd","star":3,"comment_img":"dfdfd"}]}
     */
    public function common_spot()
    {
        $map['comment_id'] = $this->request->post('comment_id');
        $commentid = $map['comment_id'];
        $map['user_id'] = $this->request->post('user_id');
        $status = $this->request->post('status');
        $data = Db::name('shop_comment_spot')->where($map)->find();

        if (!$data) {
            Db::name('shop_comment_spot')->insert($map);
            Db('shop_comment')->where('id', $commentid)->setInc('spotnum');
        } else {

            if ($status == '1') {
                if ($data['status'] == '0') {
                    Db::name('shop_comment_spot')->where($map)->update(['status' => '1']);
                    Db::name('shop_comment')->where('id', $commentid)->setDec('spotnum');
                }
            }
            if ($status == '0' || $status =='') {
                if ($data['status'] == '1') {
                    Db::name('shop_comment')->where('id', $commentid)->setInc('spotnum');
                    Db::name('shop_comment_spot')->where($map)->update(['status' => '0']);
                }
            }

        }
        $this->success('返回成功');
    }
    /**
     * @apiGroup test
     * @apiName  content_list
     * @apiDescription    问题与帮助列表
     * @api {post} /api/shop/content_list  问题与帮助列表
     * @apiparam {string} content_type      关于我们  传1 问题与帮助 传2 关于我们
     * @apiSuccessExample Success-Response:
     * {"code":1,"msg":"返回成功","time":"1577328043","data":[{"id":15,"name":"shop_comment22","createtime":1577323207}]}
     */
    public function content_list(){
        $content_type = $this->request->post('content_type');
        if($content_type == '1') {
            $map['pid'] = '14';
            $data = Db::name('category')->field('id,name,createtime,description')->where($map)->select();

        }else{
            $id=  '16';
            $data = Db::name('category')->where('id',$id)->field('id,name,createtime,description,content')->find();
        }
        if($data){
            $this->success('返回成功',$data);
        }else{
            $this->error('返回失败');
        }
    }

    /**
     * @apiGroup test
     * @apiName  content_detail
     * @apiDescription  文章详情接口
     * @api {post} /api/shop/content_detail  文章详情
     * @apiparam {string} id
     * @apiSuccessExample Success-Response:
     * {"code":1,"msg":"返回成功","time":"1577328043","data":[{"id":15,"name":"shop_comment22","createtime":1577323207}]}
     */
    public function content_detail(){
        $map['id'] = $this->request->post('id');
        $data = Db::name('category')->field('id,name,createtime,description,content')->where($map)->find();
        if($data){
            $this->success('返回成功',$data);
        }else{
            $this->error('返回失败');
        }
    }
}